var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
var QSSmartSealWX = require("../../../../utils/QS_Minprogram_SDK_V1.0");
var qssealsdk;
const app = getApp();
Page({
  data:{
    deviceId:null,
    showSearch:false,
    mac:'',
    connectStatus:false,
    checkStatus:false,
    showSealDialog:false,
    selectedSeal:null,
    sealList:[],
    rules:[
      {
        name: 'mac',
        rules: [{required: true, message: '请搜索印章!'}]
      }
    ],
    formData:{},
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '置换印章', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad() {
    requestClient = new ZYRequestClient();
  },
  onShow(){
    var _this = this;
    qssealsdk = QSSmartSealWX.getInstance();
    _this.setData({
      sealList:[]
    });
    requestClient.checkFunctionPermission(1004,'您没有权置换印章，请联系企业创建者！',function(){
      _this.loadSealList();
    },function(){
      wx.navigateBack({
        delta: 1,
      })
    });
  },
  onUnload(){
    this.disconnectDevice();
  },
  // 加载印章列表
  loadSealList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(defaultCompany == ''){
      defaultCompany = { id:0 };
    }
    requestClient.getSealList(defaultCompany.id,function(res){
      _this.setData({
        sealList:res.data.data
      });
    });
  },
  // 点击搜索印章
  bindSearchClick(e){
    var _this = this;
    // 判断是否有蓝牙权限
    wx.getSetting({
      success(res){
        if(res.authSetting["scope.bluetooth"]){
          _this.setData({
            showSearch:true,
            deviceId:null,
            checkStatus:false,
          });
          wx.showLoading({
            title: '正在搜索...',
            mask:true,
          })
          // 延时执行
          setTimeout(() => {
            _this.startDiscovery();
          }, 1500);
        } else {
          // 引导用户授权
          wx.authorize({
            scope: 'scope.bluetooth',
            success(){
              _this.setData({
                showSearch:true,
                deviceId:null,
                checkStatus:false,
              });
              wx.showLoading({
                title: '正在搜索...',
                mask:true,
              })
              // 延时执行
              setTimeout(() => {
                _this.startDiscovery();
              }, 1500);
            },
            fail(){
              // 引导用户打开设置
              wx.showModal({
                title:"蓝牙权限",
                content:'需要使用您的蓝牙搜索和启动印章',
                success(r){
                  if(r.confirm){
                    wx.openSetting({
                      success(res){
                        if(res.authSetting["scope.bluetooth"]){
                          _this.setData({
                            showSearch:true,
                            deviceId:null,
                            checkStatus:false,
                          });
                          wx.showLoading({
                            title: '正在搜索...',
                            mask:true,
                          })
                          // 延时执行
                          setTimeout(() => {
                            _this.startDiscovery();
                          }, 1500);
                        } else {
                          wx.showToast({
                            title: '暂无蓝牙权限',
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 开始搜索
  startDiscovery:function(){
    wx.hideLoading({
      success: (res) => {},
    })
    var _this = this;
    // 先关闭连接
    _this.disconnectDevice(_this._startDiscovery);
  },
  _startDiscovery(){
    var _this = this;
    qssealsdk.startDiscovery(function(res){
      if(_this.data.deviceId != null){
        return;
      }
      // 先停止搜素
      _this.stopDiscovery();
      if(res.result){
        var device = res.data;
        // 赋值
        _this.setData({
          deviceId:device.deviceId,
          mac:device.mac,
          [`formData.mac`]:device.mac,
        });
        // 获取注册设备，验证所属平台
        requestClient.getAccessDevice(_this.data.mac,function(resData){
          if(resData.data.success){
            wx.showModal({
              title:'置换失败',
              content:'此印章已注册！',
              showCancel:false,
              success(r){
              }
            })
          } else {
            wx.showModal({
              title:'注册设备',
              content:'您确定置换此印章吗？',
              success(r){
                if(r.confirm){
                  // 连接印章
                  _this.connectDevice();
                }
              }
            })
          }
        });
      } else {
        wx.showModal({
          title:'搜索失败',
          content:res.message,
          showCancel:false,
          success(r){
  
          }
        })
      }
    });
  },
  // 停止搜索
  stopDiscovery(e){
    var _this = this;
    _this.setData({
      showSearch:false
    });
    qssealsdk.stopDiscovery();
  },
  // 连接设备
  connectDevice(){
    var _this = this;
    var deviceId = _this.data.deviceId;
    if(deviceId == null){
      return;
    }
    wx.showLoading({
      title: '正在连接..',
      mask:true,
    })
    // 连接印章
    qssealsdk.connectDevice(deviceId,_this.onConnectStatusChanged);
    // 连接超时提示重连
    setTimeout(() => {
      if(!_this.data.connectStatus){
        wx.hideLoading({
          success: (res) => {},
        });
        wx.showToast({
          title: '连接失败,可以重新搜索！',
          icon:'none'
        });
      }
    }, 3000);
  },
  // 连接状态回调
  onConnectStatusChanged(res){
    var _this = this;
    if(res.data.connectStatus){
      _this.setData({
        connectStatus:true
      });
      // 延时验证密钥
      setTimeout(() => {
        // 握手
        qssealsdk.handshake(_this.onHandshakeCallBack);
      }, 2000);
    } else {
      _this.setData({
        connectStatus:false
      });
    }
  },
  // 握手回调事件
  onHandshakeCallBack(dataResult){
    var _this = this;
    wx.hideLoading({
      success: (res) => {},
    })
    // 判断验证结果
    if(dataResult.result){
      _this.setData({
        checkStatus:true,
      });
      wx.showToast({
        title: dataResult.message,
        icon:'none'
      })
    }
  },
  // 断开设备
  disconnectDevice(callback){
    var _this = this;
    _this.setData({
      connectStatus:false,
    });
    wx.hideLoading({
      success: (res) => {},
    })

    qssealsdk.disConnectDevice();
    if(callback){
      callback();
    }
  },
  // 显示申请选择印章对话框
  bindShowSelectSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:true,
    });
  },
  // 确认选择印章
  bindSealCheck(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
    var sealList = _this.data.sealList;
    for(var i=0;i<sealList.length;i++){
      if(sealList[i].id == parseInt(e.detail.value)){
        _this.setData({
          selectedSeal:sealList[i]
        });
        break;
      }
    }
  },
  // 关闭选择印章
  bindClosedSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
  },
  // 提交
  submitForm(e){
    var _this = this;
    _this.selectComponent('#form').validate((valid, errors) => {
          if (!valid) {
              const firstError = Object.keys(errors)
              if (firstError.length) {
                 // 提示用户
                wx.showToast({
                  title: errors[firstError[0]].message,
                  icon:'none'
                })
              }
          } else {
            // 判断是否选中印章
            var seal = _this.data.selectedSeal;
            if(seal == null){
              // 提示用户
              wx.showToast({
                title: '请选择印章',
                icon:'none'
              })
              return;
            }
            // 构造数据
            var userInfo = wx.getStorageSync('userInfo');
            var replaceData = {
              mac:_this.data.mac,
              sealId:seal.id,
              createUser:userInfo.id
            };
            requestClient.checkFunctionPermission(1004,'您没有权限置换印章，请联系企业创建者！',function(){
              wx.showModal({
                title:'置换印章',
                content:'您确定置换' + seal.name+'这个印章吗，置换后原来的印章将不能使用，请谨慎操作！',
                success(r){
                  if(r.confirm){
                    requestClient.replaceSeal(replaceData,function(res){
                      if(res.data.success){
                        wx.showToast({
                          title: '置换成功！',
                          icon:"none",
                          mask:true,
                          duration:2000
                        })
                        wx.navigateBack({
                          delta: 1,
                        })
                      } else {
                        if(res.data.code == 2002){
                          setTimeout(function(){
                            requestClient.getSealInfoByMac(_this.data.mac,function(res){
                                  wx.navigateTo({
                                    url: '../sealinfo/index?id=' + res.data.data.id,
                                  })
                            })
                          },2000);
                        }
                      }
                    })
                  }
                }
              })
            },function(){
              wx.navigateBack({
                delta: 1,
              })
            });
          }
      })
  }
})
